
layui.define(['table', 'reForm', 'reExcel', 'upload'], function (exports) {

    var $ = layui.$
        , layer = layui.layer
        , view = layui.view
        , admin = layui.admin
        , reForm = layui.reForm
        , reExcel = layui.reExcel
        , upload = layui.upload
        , table = layui.table

        , reTable = {
            tableReload: function (tableId) {
                table.reload(tableId + '-table');
            }
            , tableSearch: function (tableId, options) {

                var searchWhere = admin.getSearchWhere(tableId);

                if (options && options.SearchWhere && searchWhere.SearchWhere) {
                    $.merge(options.SearchWhere, JSON.parse(searchWhere.SearchWhere));
                    searchWhere.SearchWhere = JSON.stringify(options.SearchWhere);
                } else if (options && options.SearchWhere) {
                    searchWhere.SearchWhere = JSON.stringify(options.SearchWhere);
                }
                if (searchWhere.SearchWhere || options)
                    table.reload(tableId + '-table', {
                        where: $.extend(searchWhere, options ? options.where : null)
                    });
                else 
                    table.reload(tableId + '-table');
            }
            , getTableCols: function (cols, formFields) {
                $.each(formFields, function (idx, json) {

                    //if (json.elementType == 'textEdit')
                    //    return false;

                    var col = {};

                    col.field = json.itemName;
                    col.cellName = json.fieldName;
                   
                    if (json.elementType === 'imgArea') {
                        col.templet = function (d) {
                            return d[this.field] ? '<a href="javascript:;" class="layui-table-link" onclick="layui.reForm.viewImg(\'' + d[this.field] + '\')">查看</a>' : '';
                        };
                        col.excel = function (d) {
                            return d[this.field] ? (layui.setter.fileApi+d[this.field].split(';').join(' ' + layui.setter.fileApi)) : '';
                        };
                    }

                    cols.push(col);
                });
                return cols;
            }
            , getTableColsNoHide: function (cols, formFields) {
                $.each(formFields, function (idx, json) {

                    if (json.elementType === 'textEdit' || json.elementType === 'hidden')
                        return true;

                    var col = {};

                    col.field = json.itemName;
                    col.cellName = json.fieldName;
                    col.width = 200;

                    if (json.elementType === 'imgArea') {
                        col.templet = function (d) {
                            return d[this.field] ? '<a href="javascript:;" class="layui-table-link" onclick="layui.reForm.viewImg(\'' + d[this.field] + '\')">查看</a>' : '';
                        };
                        col.excel = function (d) {
                            return d[this.field] ? (layui.setter.fileApi + d[this.field].split(';').join(' ' + layui.setter.fileApi)) : '';
                        };
                    }

                    cols.push(col);
                });
                return cols;
            }
            , initTable: function (options) {
                var formOptions = options.formOptions;

                //if (options.formOptions && !options.formOptions.url && !options.formOptions.formHtml && options.formOptions.formLay) {
                //    admin.req({
                //        type: 'post'
                //        , url: '/Tool/getFormConfig'
                //        , data: { formNo: options.formOptions.formLay }
                //        , done: function (res) {
                //            if (res.data.tempForm) {
                //                options.formOptions.formLay = tableId + '-form';
                //                var subFormItemsData = layui.admin.parse(res.data.tempForm);
                //                var html = '<form class="layui-form " lay-filter="' + options.formOptions.formLay + '" id="' + options.formOptions.formLay + '">'
                //                    + admin.getFormHtml(subFormItemsData)
                //                    + admin.getFormBtn(tableId);
                //                + '</form>';
                //                options.formOptions.formHtml = html;
                //                options.formOptions.FormItemsData = subFormItemsData;

                //                formOptions = options.formOptions;
                //            }
                //        }
                //    });
                //}

                var tableId = options.tableId;

                //避免没加载到的情况
                if (options.formOptions && options.autoForm !== false && !options.formOptions.url && !options.formOptions.formHtml) {

                    var subFormNo = tableId + '-form';

                    admin.jsonData('/json/form/' + (options.formOptions.formLay || subFormNo), function (subForm) {
                        var subFormItemsData = admin.stringToObj(subForm);
                        var html = '<form class="layui-form " lay-filter="' + subFormNo + '" id="' + subFormNo + '">'
                            + layui.admin.getFormHtml(subFormItemsData)
                            + layui.admin.getFormBtn(tableId)
                            + '</form>';
                        options.formOptions.formLay = subFormNo;
                        options.formOptions.formHtml = html;
                        options.formOptions.FormItemsData = subFormItemsData;

                        formOptions = options.formOptions;
                    });
                }

                //if (options.initDataParams)
                //    $.each(options.initDataParams, function (k, v) {
                //        admin.updateDataParams(v);
                //    });

                var autoTool = options.autoTool === false ? false : true,
                    autoToolbar = options.autoToolbar === false ? false : true;

                var search = $('#' + tableId + '-search-form').length > 0;
                if (search) {

                    //if (options.autoForm !== true)
                    //    reForm.setFormLang(tableId + '-search-form');

                    var html = '<div class="layui-inline" id="' + tableId + '-form-tool">';
                    if (typeof $('#' + tableId + '-search-form').attr('nosearchbtn') === 'undefined') {
                        html += '<button class="layui-btn layui-btn-default layuiadmin-btn-admin" type="button" lay-event="search"><i class="layui-icon layui-icon-search layuiadmin-button-btn"></i></button>';
                        html += '<button class="layui-btn layui-btn-primary" type="button" lay-event="reset">' + (layui.admin.lang ? 'Reset' : '重置') + '</button>';
                    }
                    if (autoTool)
                        html += admin.getPageToolBtn(tableId);
                    html += '</div>';
                    $('#' + tableId + '-search-form').children().first().append(html);
                    $('#' + tableId + '-form-tool').find('[lay-event="import"]').attr('id', tableId + '-form-tool-import');

                    $('#' + tableId + '-search-form input:text').bind('keydown', function (event) {
                        if (event.keyCode === 13) {
                            $('#' + searchFormNo + ' [lay-event="search"]').click();
                        }
                    });

                } else {
                    if (autoTool) {
                        var toolHtml = admin.getPageToolBtn(tableId);
                        if (toolHtml.length > 0) {
                            var formHtml = '<form class="layui-form layui-card-header layuiadmin-card-header-auto" id="' + tableId + '-search-form">';
                            formHtml += '<div class="layui-form-item">';
                            formHtml += '<div class="layui-inline" id="' + tableId + '-form-tool">';
                            formHtml += toolHtml;
                            formHtml += '</div>';
                            formHtml += '</div>';
                            formHtml += '</form>';
                            $('#' + tableId + '-table').parent().before(formHtml);
                            $('#' + tableId + '-form-tool').find('[lay-event="import"]').attr('id', tableId + '-form-tool-import');
                        }
                    }
                }

                if (autoToolbar)
                    $('#' + tableId + '-toolbar').html(admin.getPageToolbarBtn(tableId));

                var tableDone = options.tableOptions.tableDone;
                delete options.tableOptions.tableDone;
                var parseData = options.tableOptions.parseData;
                delete options.tableOptions.parseData;

                var isPage = options.tableOptions.isPage;
                delete options.tableOptions.isPage;

                if (options.tableOptions.url)
                    options.tableOptions.url = (layui.setter.defaultApi || '') + options.tableOptions.url;

                var tableOptions = $.extend({
                    elem: '#' + tableId + '-table'
                    , headers: { //通过 request 头传递
                        Authorization: 'Bearer ' + (layui.data(layui.setter.tableName)[layui.setter.request.tokenName] || '')
                    }
                    , height: options.tableOptions.fullHeight !== false ? options.tableOptions.height ? options.tableOptions.height : 'full-' + Math.round($('#' + tableId + '-table').offset().top + 15) : null
                    , autoSort: isPage === false ? true : false
                    , queryReload: options.tableOptions.queryReload || false
                    , method: 'post'
                    , text: { none: ' ' }
                    , page: isPage
                    , cellMinWidth: options.tableOptions.cellMinWidth || 120
                    , limit: isPage === false ? options.tableOptions.data ? options.tableOptions.data.length : null : options.tableOptions.limit || 15
                    , limits: [10, 15, 20, 30, 40, 50, 60, 70, 80, 90]
                    , parseData: function (res) {
                        if (res.code === 1001)
                            return layui.view.exit();
                        typeof parseData === 'function' && parseData.call(this, res);
                    }, done: function (res) {
                        typeof tableDone === 'function' && tableDone.call(this, res);
                        if (options.customCss)
                            $('[lay-id="' + tableId + '-table"]').addClass(tableId + '-table');
                    }

                }, options.tableOptions);

                if (options.buildType === 1) {

                    if (options.selectType)
                        options.tableCols.unshift({ type: options.selectType, fiexd: 'left' });

                    if (options.numbers)
                        options.tableCols.unshift({ type: 'numbers', fiexd: 'left' });

                    $.each(options.tableCols, function (idx, item) {
                        item.title = item['cellName' + admin.lang];
                        delete item.cellName;
                        delete item.cellName_EN;
                        delete item.cellOrder;

                        //if (item.LAY_TABLE_INDEX)
                        //    delete item.LAY_TABLE_INDEX;
                        //if (item.width)
                        //    item.width = parseInt(item.width);
                        //if (item.minWidth)
                        //    item.minWidth = parseInt(item.minWidth);

                        if (item.field === 'tool') {
                            if (options.autoToolbar) {
                                var barHtml = admin.getPageToolbarBtn(tableId);
                                item.templet = function () {
                                    return barHtml;
                                };
                            } else if (typeof item.templetFun === 'function') {
                                item.templet = item.templetFun;
                                delete item.templetFun;
                                // var fun = (function () { var templetFun = item.templetFun; return templetFun; })();
                                //item.templet = function (d) { return fun(d); };
                                //delete item.templetFun;
                            }
                        } else {
                            if (item.templet &&typeof item.templet==='string') {
                                var templet = item.templet;
                                item.templet = function (d) {
                                    return admin.cellTemplet(templet, d[this.field]);
                                };
                            }

                            if (typeof item.templetFun === 'function') {
                                item.templet = item.templetFun;
                                delete item.templetFun;
                            }
                        }
                    });
                    tableOptions.cols = [options.tableCols];
                    table.render(tableOptions);
                }
                else {
                    admin.tableCell(tableId, function (data) {
                        if (data && data.length > 0) {
                            $.each(tableOptions.cols[0], function (idx, item) {
                                if (item.field) {
                                    var find = admin.filterList(data, { Member: item.field })[0];
                                    if (find)
                                        item.title = find['MemberName' + admin.lang] || item.title;
                                }
                            });
                        }

                        table.render(tableOptions);
                    });
                }

                var columns = [].concat.apply([], tableOptions.cols)
                    , cellTitle = {}
                    , cellWidth = {}
                    , filterExportData = {};

                var index = 0;
                for (var i = 0; i < columns.length; i++) {
                    if (columns[i].field && !columns[i].hide && columns[i].field !== 'tool') {
                        filterExportData[columns[i].field] = columns[i];
                        if (columns[i].width)
                            cellWidth[String.fromCharCode(64 + parseInt(++index))] = columns[i].width * 0.8;
                        else
                            cellWidth[String.fromCharCode(64 + parseInt(++index))] = tableOptions.cellMinWidth || 120;

                        cellTitle[columns[i].field] = columns[i].title;
                    }
                }
                $.each(filterExportData, function (k, v) {

                    filterExportData[k] = function (value, line, data) {
                        return {
                            v: v.excel ? (typeof v.excel === 'function' ? v.excel(line) : value) : v.templet ? (typeof v.templet === 'function' ? v.templet(line) : value) : value
                            , s: {
                                alignment: {
                                    horizontal: v.align
                                }
                            }
                        };
                    };
                });

                if (options.importOptions) {
                    var verifyImportFilter = {}, resVerifyImportFilter = {};
                    $.each(options.templateOptions.cellTitle, function (k, v) {
                        verifyImportFilter[k] = k;

                        resVerifyImportFilter[k] = k;
                        if (filterExportData[k])
                            resVerifyImportFilter[k] = filterExportData[k];
                    });
                    $.extend(verifyImportFilter, { ErrMsg: 'ErrMsg' });
                    $.extend(resVerifyImportFilter, { ErrMsg: 'ErrMsg' });
                    upload.render({
                        elem: '#' + tableId + '-form-tool-import' //绑定元素
                        , url: '/upload/' //上传接口（PS:这里不用传递整个 excel）
                        , auto: false //选择文件后不自动上传
                        , accept: 'file'
                        , exts: 'xlsx'
                        , choose: function (obj) {// 选择文件回调
                            console.log(obj);
                            var files = obj.pushFile();
                            //files = Object.values(files);

                            var file = {};
                            $.each(files, function (k, v) {
                                file = v;
                            });

                            //if (files.length > 1)
                            //    files.splice(0, 1);
                            reExcel.uploadExcel([file], $.extend({}, options.importOptions,
                                {
                                    cellWidth: $.extend({}, options.templateOptions.cellWidth, options.importOptions.verifyCellWidth)
                                    , cellTitle: $.extend({}, options.templateOptions.cellTitle, options.importOptions.verifyCellTitle)
                                    , verifyImportFilter: verifyImportFilter
                                    , success: function (res) {
                                        if (res.code === 0) {
                                            //reTable.tableSearch(tableId);
                                            table.reload(tableId + '-table');
                                        }
                                        if (res.code === 1) {
                                            reExcel.exportExcel(res.data, {
                                                fileName: options.importOptions.fileName
                                                , cellWidth: $.extend({}, options.templateOptions.cellWidth, options.importOptions.verifyCellWidth)
                                                , cellTitle: $.extend({}, options.templateOptions.cellTitle, options.importOptions.verifyCellTitle)
                                                , filterExportData: resVerifyImportFilter
                                                //, filterExportData: options.importOptions.verifyImportFilter
                                                //, handleImportFilter: options.importOptions.handleImportFilter
                                            });
                                        }
                                    }
                                }
                            ));

                            $(".layui-upload-file").val('');
                        }
                    });
                }

                table.on('sort(' + tableId + '-table)', function (obj) {
                    if (isPage === false ? false : true)
                        table.reload(tableId + '-table', {
                            initSort: obj
                            , page: isPage
                            , where: { order: obj.field + (obj.type ? ' ' + obj.type : '') }
                        });
                });

                //监听操作按钮
                var toolFun = $.extend({
                    search: function () {
                        table.reload(tableId + '-table', {
                            where: $.extend({}, tableOptions.where, admin.getSearchWhere(tableId))
                        });
                    }
                    , reset: function () {
                        $('#' + tableId + '-search-form')[0].reset();

                        $.each(options.searchForm.searchFormItemsData, function (idx, json) {
                            reForm.bindFormHtml(json, null, options.searchForm.searchFormNo);
                        });

                        table.reload(tableId + '-table', {
                            page: isPage
                            , where: $.extend({ SearchWhere: null }, tableOptions.where)
                        });
                    }
                    , batchdel: function () {
                        if (toolFun['before_batchdel'] ? toolFun['before_batchdel'].apply(this) : true)
                            if (options.delUrl) {

                                var checkStatus = table.checkStatus(tableId + '-table')
                                    , checkData = checkStatus.data; //得到选中的数据

                                if (checkData.length === 0)
                                    return layer.msg(layui.admin.lang ? 'Please select data.' : '请选择数据。');


                                var arr = [];
                                $.each(checkData, function (idx, json) {
                                    arr.push(json[tableOptions.idField]);
                                });

                                view.confirm('', {
                                    title: admin.getToolFormTitle(tableId, 'batchdel')
                                    , doyes: function () {
                                        admin.req({
                                            url: options.delUrl
                                            , type: 'post'
                                            , data: { ids: arr.join(',') }
                                            , loading: options.postLoad || true
                                            , tipOk: options.tipOk || true
                                            , done: function (res) {
                                                //reTable.tableSearch(tableId);
                                                table.reload(tableId + '-table');
                                                toolFun['batchdel_success'] ? toolFun['batchdel_success'].call(this, res) : '';
                                            }
                                        });
                                    }
                                });
                            }
                    }
                    , clear: function () {
                        if (options.clearUrl)
                            view.confirm('', {
                                title: admin.getToolFormTitle(tableId, 'clear')
                                , doyes: function () {
                                    admin.req({
                                        url: options.clearUrl
                                        , type: 'post'
                                        , loading: options.postLoad || true
                                        , tipOk: options.tipOk || true
                                        , done: function (res) {
                                            //reTable.tableSearch(tableId);
                                            table.reload(tableId + '-table');
                                            toolFun['clear_success'] ? toolFun['clear_success'].call(this, res) : '';
                                        }
                                    });
                                }
                            });
                    }
                    , add: function () {
                        if (toolFun['before_add'] ? toolFun['before_add'].apply(this) : true)
                            reForm.popupForm($.extend({}, formOptions, {
                                title: admin.getToolFormTitle(tableId, 'add')
                                , formLay: formOptions.formLay || tableId + '-form'
                                , initData: typeof formOptions.initData === 'function' ? formOptions.initData.call(this) : formOptions.initData
                                , done: function (res) {
                                    table.reload(tableId+'-table');
                                    //reTable.tableSearch(tableId);
                                    toolFun['add_success'] ? toolFun['add_success'].call(this, res) : '';
                                }
                            }));
                    }
                    , template: function () {
                        reExcel.exportExcel([], options.templateOptions);
                    }
                    , export: function() {
                        admin.req({
                            api: '',
                            url: tableOptions.url,
                            type: 'post',
                            data: $.extend({}, tableOptions.where, admin.getSearchWhere(tableId)),
                            loading: true,
                            tipOk: true,
                            done: function(res) {
                                console.log(res)
                                if (typeof parseData === 'function')
                                    $.each(res.data,
                                        function(idx, data) {
                                            if (data.FormData) {
                                                $.extend(data, JSON.parse(data.FormData));
                                                delete data.FormData;
                                            }
                                        });

                                reExcel.exportExcel(res.data,
                                    $.extend({},
                                        options.exportOptions,
                                        {
                                            cellTitle: cellTitle,
                                            cellWidth: cellWidth,
                                            filterExportData: filterExportData
                                        }));
                            }
                        });
                    }, customExport: function (obj) {
                        admin.req({
                            url: tableOptions.url
                            , type: 'post'
                            , data: $.extend(tableOptions.where, R.getSearchWhere(tableId))
                            , loading: options.postLoad || true
                            , tipOk: options.tipOk || true
                            , success: function (res) {

                                if (res.code === 0)
                                    reExcel.exportExcel(res.data, options.exportOptions);
                            }
                        });
                    }

                }, options.toolFun);
                $('#' + tableId + '-form-tool .layui-btn').on('click', function () {
                    var type = $(this).attr('lay-event');
                    toolFun[type] ? toolFun[type].call(this) : '';
                });
                //监听操作列
                var toolbarFun = $.extend({
                    edit: function (data, obj) {
                        reForm.popupForm($.extend({}, formOptions, {
                            title: admin.getToolbarFormTitle(tableId, 'edit')
                            , formLay: formOptions.formLay || tableId + '-form'
                            , initData: $.extend({}, typeof formOptions.initData === 'function' ? formOptions.initData.call(this) : formOptions.initData, data)
                            , done: function (res) {
                                if (!tableOptions.queryReload && res.updateData)
                                    obj.update(res.updateData);//不刷新更新
                                else {
                                    //reTable.tableSearch(tableId);
                                    table.reload(tableId + '-table');
                                }

                                toolbarFun['edit_success'] ? toolbarFun['edit_success'].call(this, res) : '';
                            }
                        }));
                    }
                    , del: function (data, obj) {
                        if (toolbarFun['before_del'] ? toolbarFun['before_del'].apply(this) : true)
                            if (options.delUrl)
                                view.confirm('', {
                                    title: admin.getToolbarFormTitle(tableId, 'del')
                                    , doyes: function () {
                                        admin.req({
                                            url: options.delUrl
                                            , type: 'post'
                                            , data: { ids: data[tableOptions.idField] }
                                            , loading: options.postLoad || true
                                            , tipOk: options.tipOk || true
                                            , done: function (res) {
                                                if (!tableOptions.queryReload)
                                                    obj.del();//不刷新删除
                                                else {
                                                    //reTable.tableSearch(tableId);
                                                    table.reload(tableId + '-table');
                                                }
                                                toolbarFun['del_success'] ? toolbarFun['del_success'].call(this, res) : '';
                                            }
                                        });
                                    }
                                });
                    }
                }, options.toolbarFun);
                table.on('tool(' + tableId + '-table)', function (obj) {

                    var data = obj.data;
                    var type = obj.event;
                    toolbarFun[type] ? toolbarFun[type].call(this, data, obj) : '';
                });

                //其他事件
                typeof options.tableEvent === 'function' && options.tableEvent.call(this);
            }
        };

    exports('reTable', reTable);
});